<template>
    <hr>
    <div style="padding: 20px;">子组件 {{ title }}</div>
    <hr>
    <div style="margin:20px 0px;">
        <input v-model="keyWord" placeholder="搜索" type="text">
    </div>
    <table border width="600" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <th>物品名称</th>
                <th>物品单价</th>
                <th>物品数量</th>
                <th>物品总价</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(item,index) in seachGoods" :key="index">
                <td align="center">{{ item.name }}</td>
                <td align="center">{{ item.price }}</td>
                <td align="center">{{ item.num }}</td>
                <td align="center"><button @click="item.num >1 ? item.num--: null ">-</button> {{ item.price * item.num }} <button @click="item.num <99 ? item.num ++: null ">+</button></td>
                <td align="center"><button @click="delGool(index)">删除</button></td>
                <td><button @click="chuandi(item)">给父组件传值</button></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5" align="right">
                    总价：{{ total }}
                </td>
            </tr>
        </tfoot>
    </table>
</template>

<script setup lang="ts">
import { getCurrentInstance,computed, reactive, ref } from 'vue';
const props = defineProps({
    title:{
        type: String,
        default:''
    }
})

// 给父组件 传递 值
const emit = defineEmits(['OnSend'])
const chuandi = (item)=>{
    emit('OnSend', `子组件给父组件传递的值--${item.name}`)
}


// 输出组件实例
const aa =getCurrentInstance()
console.log(aa);

let keyWord = ref<string>('')
interface Data{
    name: string,
    price:number,
    num: number
}
const goodsList = reactive<Data[]>([
    {
        name: '雨伞',
        price:20,
        num: 10
    },
    {
        name: '茶杯',
        price:100,
        num: 3
    },
    {
        name: '手机',
        price:4399,
        num: 1
    },
    {
        name: '电脑',
        price:9999,
        num: 1
    }
])

 const total=computed(()=>{
   return goodsList.reduce((prev:number,next:Data)=>{
        return prev + next.num * next.price
    },0) 
 })

  const seachGoods = computed(()=>{
    return goodsList.filter((item:Data)=>{
        return item.name.includes(keyWord.value)
    })
  })

const delGool =(index:number)=>{
    goodsList.splice(index,1)
}


// 将子组件的身上的属性和方法暴露出去
defineExpose({
    name: goodsList,
    delGool
})
</script>
